package com.lx.javasunmmrize.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description lock版本生产者和消费者问题
 * AB线程,    A+1,B-1，
 * 问题： 2个线程，没问题，4个线程或更多线程还安全吗？(不安全)
 * 原因:if判断可能会造成虚假唤醒
 * 解决问题:使用while判断
 *
 * TODO:不加synchronized会报错？死锁？
 *
 * <p>
 * 判断等待,业务,通知
 * @Author lx
 * @Date 2021/3/2 23:32
 **/
public class PrivateConsumer02 {
    public static void main(String[] args) {
        Data2 data2 = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

class Data2 {

    private int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    //+1
    public synchronized void increment() throws InterruptedException {

        try {
            lock.lock();
//        if (num!=0){
            if (num != 0) {
                //等待
                //this.wait();
                condition.await();
                System.out.println(Thread.currentThread().getName() + "=========>" + num);
            }
            num++;
            //通知其他线程,唤醒全部
//        this.notify();
            condition.notify();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    //-1
    public  void decrement() throws InterruptedException {

        try {
            lock.lock();
//        if (num!=0){
            if (num == 0) {
                //等待
                //this.wait();
                condition.await();
                System.out.println(Thread.currentThread().getName() + "=========>" + num);
            }
            num--;
            //通知其他线程,唤醒全部
//        this.notify();
            condition.notify();
        }catch (Exception e){
            e.printStackTrace();
        }  finally {
            lock.unlock();
        }
    }
}